import { ref, watchEffect } from 'vue'

export function useStorage(key, defaultValue = null, options = {}) {
  const {
    type = 'local', // 'local' 或 'session'
    encrypt = false // 是否加密
  } = options

  const storage = type === 'session' ? sessionStorage : localStorage

  // 加密解密方法
  const process = {
    encrypt: str => encrypt ? btoa(encodeURIComponent(str)) : str,
    decrypt: str => encrypt ? decodeURIComponent(atob(str)) : str
  }

  // 读取初始值
  const data = ref(defaultValue)
  try {
    const rawValue = storage.getItem(key)
    if (rawValue) {
      data.value = JSON.parse(process.decrypt(rawValue))
    }
  } catch (e) {
    console.error('Storage read error:', e)
  }

  // 自动保存变化
  watchEffect(() => {
    try {
      if (data.value === null || data.value === undefined) {
        storage.removeItem(key)
      } else {
        storage.setItem(key, process.encrypt(JSON.stringify(data.value)))
      }
    } catch (e) {
      console.error('Storage write error:', e)
    }
  })

  return data
}